package com.JL.PS;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ServerDemo extends HttpServlet{
    private Statement statement;
    private Connection conn;
    private  ResultSet resultSet;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //这里加载数据库信息
        try {
            resp.setContentType("application/json;charset=utf-8");
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/province_city","root","root");
            statement = conn.createStatement();
            resultSet = statement.executeQuery("select * from provice");
            List<Provice> provices = new ArrayList<>();
            while (resultSet.next()){
                Provice provice = new Provice();
                provice.setId(resultSet.getInt("id"));
                provice.setName(resultSet.getString("name"));
                provices.add(provice);
            }
            String result = JSON.toJSONString(provices);
            resp.getWriter().write(result);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                resultSet.close();
                statement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
